<template>
  <div class="order-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="订单号">
        <el-input
          v-model="filters.search"
          placeholder="请输入订单号、所属团长或收货地址"
          clearable
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="filters.status" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="待付款" value="待付款" />
          <el-option label="待发货" value="待发货" />
          <el-option label="待提货" value="待提货" />
          <el-option label="待评价" value="待评价" />
          <el-option label="退款中" value="退款中" />
          <el-option label="已退款" value="已退款" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="用户ID">
        <el-input
          v-model="filters.userId"
          placeholder="请输入用户ID"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计栏 -->
    <div class="stat-bar">
      <el-tag type="info">总订单数: {{ stat.totalOrders }}</el-tag>
      <el-tag type="success">待发货: {{ stat.pendingShipment }}</el-tag>
      <el-tag type="warning">待付款: {{ stat.pendingPayment }}</el-tag>
      <el-tag type="danger">退款中: {{ stat.refunding }}</el-tag>
    </div>

    <!-- 表格 -->
    <el-table 
      :data="orderList" 
      border 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="orderId" label="订单号" width="180" />
      <el-table-column prop="userId" label="用户ID" width="120" />
      <el-table-column prop="caption" label="所属团长" width="200" />
      <el-table-column label="订单金额" width="120">
        <template #default="{ row }">
          <span v-if="row.calculatedTotal !== undefined">¥{{ row.calculatedTotal }}</span>
          <span v-else>计算中...</span>
        </template>
      </el-table-column>
      <el-table-column prop="deliveryAddress" label="收货地址" width="250" />
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentMethod" label="支付方式" width="100" />
      <el-table-column prop="orderTime" label="下单时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.orderTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="onViewDetail(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span class="value">{{ currentOrder.orderId }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户ID：</span>
                <span class="value">{{ currentOrder.userId }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单状态：</span>
                <el-tag :type="getStatusType(currentOrder.status)" size="small">
                  {{ currentOrder.status }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">支付方式：</span>
                <span class="value">{{ currentOrder.paymentMethod || '未支付' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">订单金额：</span>
                <span class="value amount">¥{{ currentOrder.calculatedTotal || '计算中...' }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span class="value">{{ formatDate(currentOrder.orderTime) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 收货信息 -->
        <div class="detail-section">
          <h3 class="section-title">收货信息</h3>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ currentOrder.deliveryAddress }}</span>
          </div>
          <div class="info-item">
            <span class="label">所属团长：</span>
            <span class="value">{{ currentOrder.caption }}</span>
          </div>
        </div>

        <!-- 订单备注 -->
        <div class="detail-section" v-if="currentOrder.remark">
          <h3 class="section-title">订单备注</h3>
          <div class="remark-content">
            {{ currentOrder.remark }}
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="确认发货"
      width="500px"
    >
      <div v-if="currentOrder">
        <p>确认将订单 <strong>{{ currentOrder.orderId }}</strong> 标记为已发货？</p>
        <p>所属团长：{{ currentOrder.caption }}</p>
        <p>收货地址：{{ currentOrder.deliveryAddress }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 响应式数据
const loading = ref(false);
const orderList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const detailDialogVisible = ref(false);
const shipDialogVisible = ref(false);
const currentOrder = ref(null);
const detailLoading = ref(false);

// 筛选条件
const filters = reactive({
  search: "",
  status: "",
  dateRange: [],
  userId: ""
});

// 统计数据
const stat = reactive({
  totalOrders: 0,
  pendingShipment: 0,
  pendingPayment: 0,
  refunding: 0
});

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...filters,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    };

    const response = await axios.get('http://localhost:3000/hy/orders', { params });
    
    if (response.data.code === 200) {
      orderList.value = response.data.data.list;
      total.value = response.data.data.total;
      
      // 计算每个订单的总金额
      await calculateAllOrderTotals();
      
      // 更新统计数据
      updateStats();
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStats = () => {
  stat.totalOrders = total.value;
  stat.pendingShipment = orderList.value.filter(order => order.status === '待发货').length;
  stat.pendingPayment = orderList.value.filter(order => order.status === '待付款').length;
  stat.refunding = orderList.value.filter(order => order.status === '退款中').length;
};

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    const response = await axios.get(`http://localhost:3000/hy/orders/${orderId}`);
    
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取订单详情失败');
      return null;
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
    return null;
  }
};

// 更新订单状态
const updateOrderStatus = async (orderId, status) => {
  try {
    const response = await axios.put(`http://localhost:3000/hy/orders/${orderId}/status`, { status });
    
    if (response.data.code === 200) {
      ElMessage.success('订单状态更新成功');
      fetchOrders(); // 重新获取列表
      return true;
    } else {
      ElMessage.error(response.data.message || '更新订单状态失败');
      return false;
    }
  } catch (error) {
    console.error('更新订单状态失败:', error);
    ElMessage.error('更新订单状态失败');
    return false;
  }
};

// 事件处理
const onSearch = () => {
  currentPage.value = 1;
  fetchOrders();
};

const onReset = () => {
  Object.assign(filters, {
    search: "",
    status: "",
    dateRange: [],
    userId: ""
  });
  currentPage.value = 1;
  fetchOrders();
};

const onPageChange = (page) => {
  currentPage.value = page;
  fetchOrders();
};

const onSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchOrders();
};

const onViewDetail = async (row) => {
  try {
    detailLoading.value = true;
    currentOrder.value = row;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
  } finally {
    detailLoading.value = false;
  }
};

const onShip = (row) => {
  currentOrder.value = row;
  shipDialogVisible.value = true;
};

const confirmShip = async () => {
  if (!currentOrder.value) return;
  
  const success = await updateOrderStatus(currentOrder.value.orderId, '待提货');
  if (success) {
    shipDialogVisible.value = false;
  }
};



// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('zh-CN');
};

const getStatusType = (status) => {
  const statusMap = {
    '待付款': 'warning',
    '待发货': 'info',
    '待提货': 'primary',
    '待评价': 'success',
    '退款中': 'danger',
    '已退款': 'danger',
    '已取消': 'info'
  };
  return statusMap[status] || 'info';
};

// 商品价格缓存
const productPriceCache = new Map();

// 获取商品价格
const getProductPrice = async (productId) => {
  // 先从缓存中查找
  if (productPriceCache.has(productId)) {
    return productPriceCache.get(productId);
  }
  
  try {
    // 从商品表获取价格
    const response = await axios.get(`http://localhost:3000/hy/getproduct/${productId}`);
    if (response.data.code === 200 && response.data.data) {
      const price = parseFloat(response.data.data.currentPrice);
      if (!isNaN(price) && price >= 0) {
        // 缓存价格
        productPriceCache.set(productId, price);
        return price;
      }
    }
  } catch (error) {
    console.error(`获取商品价格失败: ${productId}`, error);
  }
  
  return 0;
};

// 计算所有订单的总金额
const calculateAllOrderTotals = async () => {
  for (const order of orderList.value) {
    order.calculatedTotal = await calculateOrderTotal(order);
  }
};

// 计算订单总金额
const calculateOrderTotal = async (order) => {
  // 参数验证
  if (!order) {
    console.warn('calculateOrderTotal: order参数为空');
    return '0.00';
  }

  // 如果订单有products数组，根据products计算总金额
  if (order.products && Array.isArray(order.products) && order.products.length > 0) {
    let total = 0;
    
    // 异步获取所有商品价格并计算总金额
    for (const product of order.products) {
      if (!product) continue;
      
      const productId = product.productId;
      const quantity = parseInt(product.quantity) || 0;
      
      if (!productId || isNaN(quantity) || quantity < 0) {
        console.warn(`商品数据无效:`, product);
        continue;
      }
      
      const price = await getProductPrice(productId);
      total += price * quantity;
    }
    
    return total.toFixed(2);
  }
  
  // 如果没有products数组或为空，使用数据库中的totalPrice字段
  if (order.totalPrice !== undefined && order.totalPrice !== null) {
    const totalPrice = parseFloat(order.totalPrice);
    if (!isNaN(totalPrice) && totalPrice >= 0) {
      return totalPrice.toFixed(2);
    }
  }
  
  // 兜底返回0
  console.warn('calculateOrderTotal: 无法计算订单金额，返回0', order);
  return '0.00';
};

// 初始化
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.filter-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-bar {
  margin-bottom: 20px;
}

.stat-bar .el-tag {
  margin-right: 15px;
  font-size: 14px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

/* 订单详情样式 */
.order-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  line-height: 1.5;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
}

.value {
  color: #303133;
  flex: 1;
}

.value.amount {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

.remark-content {
  background: #fff;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #606266;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .label {
    margin-bottom: 4px;
  }
}
</style>